package world.snowcrystal.openapi.controller;

import org.apache.commons.lang3.time.DateUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import world.snowcrystal.commons.model.dto.BaseResponse;
import world.snowcrystal.commons.model.entity.DailyInvokeLog;
import world.snowcrystal.commons.model.entity.InterfaceInvokeAnalysis;
import world.snowcrystal.commons.model.enums.UserRoleEnum;
import world.snowcrystal.commons.model.vo.InterfaceTotalInvokeCountVO;
import world.snowcrystal.commons.model.vo.RecentInvokeCountVO;
import world.snowcrystal.commons.service.AnalysisService;
import world.snowcrystal.openapi.annotation.AuthorityCheck;
import world.snowcrystal.openapi.utils.ResultUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/analysis")
public class AnalysisController {

    private AnalysisService analysisService;


    public AnalysisController(AnalysisService analysisService) {
        this.analysisService = analysisService;
    }


    @GetMapping("/top10")
    @AuthorityCheck(UserRoleEnum.ADMIN)
    public BaseResponse<List<InterfaceTotalInvokeCountVO>> listTop10InvokedInterface() {
        List<InterfaceInvokeAnalysis> userInvokeLogs = analysisService.retrieveTopNInvokedInterface(10);

        return ResultUtils.success(userInvokeLogs
                .stream().map(InterfaceTotalInvokeCountVO::fromEntity)
                .collect(Collectors.toList()));
    }

    @GetMapping("/recent-invoke-count/{days}")
    @AuthorityCheck(UserRoleEnum.ADMIN)
    public BaseResponse<List<RecentInvokeCountVO>> retrieveRecentDaysInvokeCount(@PathVariable(name = "days", required = false) Integer days) {

        int recent = Optional.ofNullable(days).orElse(10);

        Date now = new Date();
        Date start = DateUtils.addDays(now, -recent);
        List<DailyInvokeLog> dailyInvokeLogs = analysisService.retrieveRecentInvokeLog(start, now);
        return ResultUtils.success(dailyInvokeLogs.stream().map(RecentInvokeCountVO::fromEntity).toList());
    }

}
